package com.example.midushop.controller;

import com.example.midushop.service.brand.impl.BrandServiceImpl;
import com.example.midushop.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/** 品牌信息API接口类控制器*/
@RestController
@RequestMapping("/api/BrandFind")
public class Brandind {
    @Autowired
    BrandServiceImpl brandService;

    /**根据编号查询所有品牌信息，若编号为空则查询所有*/
    @GetMapping("/getBrandAll")
    public R findBrandAll(@RequestParam(required = false) long brand_id,@RequestParam(required = false,defaultValue = "") String brandName){
        return R.ok(brandService.findAllBrand(brand_id,brandName));
    };

    @Value("${prop.up-folder-BrandImage}")
    String up_folder;
    @PostMapping("/addBrand")
    public R addBrand(@RequestParam(required = false,defaultValue = "") String brandName, @RequestPart("file") MultipartFile[] findImage) throws IOException {
        if(findImage.length>0){
            //遍历文件
            for (MultipartFile multipartFile : findImage) {
                if(!multipartFile.isEmpty()){
                    String originalFilename = multipartFile.getOriginalFilename();
                    String newname= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
                    //文件保存路径
                    String path=up_folder+"\\"+newname;
                    multipartFile.transferTo(new File(path));
                    //存入数据库
                    brandService.addBrand(brandName,newname,"H",1,new Date(),new Date());
                }
            }
        }
        return R.ok(brandService.findAllBrand(0,brandName)); //返回当前添加的品牌对象
    };
}
